package org.jim.server.listener;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImSessionContext;
import org.jim.core.cache.redis.RedisCacheManager;
import org.jim.core.config.ImConfig;
import org.jim.core.message.MessageHelper;
import org.jim.core.packets.User;
import org.jim.core.packets.UserStatusType;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;

/**
 * @ClassName DefaultImServerListener
 * @Description 默认IM服务端连接监听器
 * @Author WChao
 * @Date 2020/1/4 11:15
 * @Version 1.0
 **/
public class DefaultImServerListener implements ImServerListener {
	

    @Override
    public boolean onHeartbeatTimeout(ImChannelContext channelContext, Long interval, int heartbeatTimeoutCount) {
    	//System.out.println("服务器心跳监测："+channelContext.getUserId()+":"+interval+":"+heartbeatTimeoutCount);
    	
    	ImSessionContext imSessionContext = channelContext.getSessionContext();
		User clientUser = imSessionContext.getImClientNode().getUser();
		clientUser.setStatus(UserStatusType.OFFLINE.getStatus());
		
		ImServerConfig imServerConfig = ImConfig.Global.get();
		MessageHelper messageHelper = imServerConfig.getMessageHelper();
		messageHelper.updateUserTerminal(clientUser);
    	//TODO 加入心跳日志
//    	if( interval > 3) {
//    		//初始化计时器
//    		channelContext.getTioChannelContext().stat.heartbeatTimeoutCount.set(0);
//    		ImSessionContext imSessionContext = channelContext.getSessionContext();
//    		User clientUser = imSessionContext.getImClientNode().getUser();
//    		clientUser.setStatus(UserStatusType.OFFLINE.getStatus());
//    		
//    		ImServerConfig imServerConfig = ImConfig.Global.get();
//    		MessageHelper messageHelper = imServerConfig.getMessageHelper();
//    		messageHelper.updateUserTerminal(clientUser);
//    		//JimServerAPI.close(channelContext,"客户端链接服务心跳超时" );
//    		//TODO 监测一下是否还需要手动更改缓存中用户当前状态
//    		//RedisCacheManager.getCache(USER).put(userId+SUFFIX+TERMINAL+SUFFIX+terminal, user.getStatus());
//    	}
    	
    	return false;
    }

    @Override
    public void onAfterConnected(ImChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {

    }

    @Override
    public void onAfterDecoded(ImChannelContext channelContext, ImPacket packet, int packetSize) throws Exception {

    }

    @Override
    public void onAfterReceivedBytes(ImChannelContext channelContext, int receivedBytes) throws Exception {

    }

    @Override
    public void onAfterSent(ImChannelContext channelContext, ImPacket packet, boolean isSentSuccess) throws Exception {

    }

    @Override
    public void onAfterHandled(ImChannelContext channelContext, ImPacket packet, long cost) throws Exception {

    }

    @Override
    public void onBeforeClose(ImChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
    }
}
